import { $get } from './ajax'
import Vue from 'vue'
import request from '../common/ajax/request'
// 需要的时候一次请求数据，多次使用

const userInfo = { // 用户信息
  name: 'userInfo',
  default: undefined,
  ajax: async () => {
    const r = await request({method: 'GET', url: 'member/getUserId'})
    if (r.code != 200) return
    return r.obj || null
  }
}

const companyInfo = { // 公司信息
  name: 'companyInfo',
  default: undefined,
  ajax: async () => {
    const r = await request({method: 'GET', url: 'company/getCompanyByAppid'})
    document.title = r.obj.companyName
    if (r.code != 200) return
    return r.obj || null
  }
}
const shopList = { // 门店
  name: 'shopList',
  ajax: async () => {
    let {obj, code} = await $get('admin/shop/getShopByCompanyId')
    if (code != 200) return
    return obj || []
  }
}

const memberList = { // 会员组
  name: 'memberList',
  ajax: async () => {
    let {obj, code} = await $get('admin/member/getMemberTypeByCompanyId')
    if (code != 200) return
    const list = obj || []
    // stupidbackend
    list.sort((a, b) => a.minIntegral - b.minIntegral)
    return list
  }
}

let ajaxs = [userInfo, companyInfo, shopList, memberList]

function vue_async_global (ajaxs) {
  const data = {}
  const computed = {}
  const methods = {}
  ajaxs.forEach(({name, ajax}) => {
    const data_name = `${name}_`

    const methods_name_async = `${name}Async`
    const methods_name_update = `${name}Update`
    data[data_name] = arguments[0].default || []

    // 获取数据
    computed[name] = function () {
      this[methods_name_async]()
      return this[data_name]
    }

    // 获取单列 promise,并请求更新数据
    methods[methods_name_async] = function (update = false) {
      let current_fun = methods[methods_name_async]
      if (current_fun._promise == null || update) {
        return methods[methods_name_update].call(this)
      }
      return current_fun._promise
    }

    // 更新获取数据，并返回promise
    methods[methods_name_update] = function () {
      return methods[methods_name_async]._promise = new Promise(async (resolve, reject) => {
        resolve(this[data_name] = await ajax())
      })
    }
  })

  return new Vue({
    data: () => data,
    computed: {
      ...computed
    },
    methods
  })
}

window.$g = Vue.prototype.$g = vue_async_global(ajaxs)
